<template>
  <div class="pagination">
    <button @click="changepage(currentPage - 1)" :disabled="currentPage < 2">
      上一页
    </button>
    <button v-if="startEndPage.start > 1" @click="changepage(1)">1</button>

    <button v-if="startEndPage.start > 2">···</button>

    <button
      :class="{ active: currentPage === item }"
      v-for="item in startEndPage.end"
      :key="item"
      v-show="item >= startEndPage.start"
      @click="changepage(item)">
      {{ item }}
    </button>

    <button v-if="startEndPage.end < totalPage - 1">···</button>
    <button v-if="startEndPage.end < totalPage" @click="changepage(totalPage)">
      {{ totalPage }}
    </button>
    <button
      @click="changepage(currentPage + 1)"
      :disabled="currentPage > totalPage - 1">
      下一页
    </button>

    <button style="margin-left: 30px">共 {{ total }} 条</button>
  </div>
</template>

<script>
export default {
  name: "Pagination",
  data() {
    return {
      // 中间显示的页码条数
      continuePage: 5,
    };
  },
  props: ["total", "totalPage", "currentPage"],
  computed: {
    startEndPage() {
      let start, end;

      if (this.continuePage > this.totalPage) {
        (start = 1), (end = this.totalPage);
      } else {
        start = this.currentPage - Math.floor(this.continuePage / 2);
        end = this.currentPage + Math.floor(this.continuePage / 2);
        if (start < 1) {
          start = 1;
          end = this.continuePage;
        }
        if (end > this.totalPage) {
          end = this.totalPage;
          start = this.totalPage - this.continuePage + 1;
        }
      }
      return {
        start,
        end,
      };
    },
  },
  methods: {
    changepage(num) {
      this.$bus.$emit("changepage", num);
    },
  },
};
</script>

<style lang="less" scoped>
.pagination {
  button {
    margin: 0 5px;
    background-color: #f4f4f5;
    color: #606266;
    outline: none;
    border-radius: 2px;
    padding: 0 4px;
    vertical-align: top;
    display: inline-block;
    font-size: 13px;
    min-width: 35.5px;
    height: 28px;
    line-height: 28px;
    cursor: pointer;
    box-sizing: border-box;
    text-align: center;
    border: 0;

    &[disabled] {
      color: #c0c4cc;
      cursor: not-allowed;
    }

    &.active {
      cursor: not-allowed;
      background-color: #409eff;
      color: #fff;
    }
  }
}
</style>
